package com.atguigu.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有分类
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        //组装成父子树形结构
        List<CategoryEntity> resultList = entityList.stream()
                .filter(entity -> entity.getParentCid() == 0
                ).map(item -> {
                    //递归查询子树
                    List<CategoryEntity> childrenTree = getChildrenTree(item, entityList);
                    item.setChildren(childrenTree);
                    return item;
                }).sorted((item1,item2) -> {
                  return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
                }).collect(Collectors.toList());
        return resultList;
    }

    @Override
    public void removeMenuByIds(List<Long> catIds) {
        //TODO 后续根据业务需求确定删除逻辑
        //1、检查当前删除的菜单是否被其他地方引用，如有有引用则不能删除

        baseMapper.deleteBatchIds(catIds);
    }

    /**
     * 递归查询分类树形结构
     * @param entity
     * @param allList
     * @return
     */
    public List<CategoryEntity> getChildrenTree(CategoryEntity entity, List<CategoryEntity> allList) {
        List<CategoryEntity> children = allList.stream()
                .filter(item -> {
                    return item.getParentCid().equals(entity.getCatId());
                }).map(item -> {
                    item.setChildren(getChildrenTree(item, allList));
                    return item;
                }).sorted((item1,item2) -> {
                    return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
                }).collect(Collectors.toList());

        return children;
    }
}